/**
 * 漆水河 脚手架基础公开课
 * 2022/8/13 --- 2022/12/13
 * 有疑问可加QQ群: 809126489，后续会持续输出与大家一起成长
 */
package com.qishuihe.common.domain.login.impl;

import com.alibaba.fastjson.JSONObject;
import com.qishuihe.basedomain.infrastructure.vo.LoginUserVO;
import com.qishuihe.common.domain.login.LoginService;
import com.qishuihe.baseinterface.basevo.vo.BaseVO;
import com.qishuihe.baseinterface.basevo.vo.LoginResultVO;
import com.qishuihe.outbound.login.UserDTO;
import com.qishuihe.baseinterface.utils.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public LoginResultVO login(UserDTO userDTO) {
        LoginResultVO loginResultVO = new LoginResultVO();
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userDTO.getUsername(), userDTO.getPassword());
        Authentication authentication =authenticationManager.authenticate(usernamePasswordAuthenticationToken);
        if(null==authentication){
            throw new RuntimeException("认证失败");
        }
        LoginUserVO loginUserVO = (LoginUserVO)authentication.getPrincipal();
        String username= loginUserVO.getUsername();
        //用登录账号生成token，把token传到请求方，作为下次访问的凭证
        stringRedisTemplate.opsForValue().set(username, JSONObject.toJSONString(loginUserVO));
        loginResultVO.setToken(JWTUtil.createJWT(username));
        //loginUserVO 存在分布式缓存里，作
        return loginResultVO;
    }

    @Override
    public BaseVO logout(UserDTO userDTO) {

        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginUserVO loginUserDTO = (LoginUserVO)usernamePasswordAuthenticationToken.getPrincipal();
        String username= loginUserDTO.getUsername();
        //用登录账号生成token，把token传到请求方，作为下次访问的凭证
        boolean flag =  stringRedisTemplate.delete(username);
        BaseVO baseVO = new BaseVO();
        baseVO.setMessage("登出成功");
        return baseVO;
    }

}
